package dyy.zc.alumnibook.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import dyy.zc.alumnibook.R;
import dyy.zc.alumnibook.application.MyApplication;
import dyy.zc.alumnibook.base.BaseActivity;
import dyy.zc.alumnibook.bean.PhotoAlbum;
import dyy.zc.alumnibook.bean.UserInfo;
import dyy.zc.alumnibook.permission.PermissionsChecker;
import dyy.zc.alumnibook.ui.adapter.ImgAdapter;
import dyy.zc.alumnibook.utils.BmobUtils;
import dyy.zc.alumnibook.utils.ImageUploadUtil;
import dyy.zc.alumnibook.utils.ImageUtil;
import dyy.zc.alumnibook.utils.ToastUtils;
import dyy.zc.alumnibook.views.ActionSheet;
import dyy.zc.alumnibook.views.EmptyView;
import dyy.zc.alumnibook.views.MyAlertDialog;

public class PhotoActivity extends BaseActivity implements View.OnClickListener ,ActionSheet.OnSheetItemClickListener{

    public static int type = 0;
    private final int SUCCESS = 1;
    private final int PIC_SUCCESS = 2;
    private final int SAVE_SUCCESS = 3;
    //拍照、从相册选择、照片保存成功
    private final int TAKE_PHOTO = 1, CHOOSE_PHOTO = 2, SAVE_IMAGE_SUCCESS = 3;
    private final int REQUEST_CODE = 0;
    public ImageView civ_head;
    private TextView title,add;
    private RecyclerView recyclerView;
    private ImgAdapter adapter;
    private List<BmobFile> list = new ArrayList<>();
    private BmobUtils bmobUtils;
    private EmptyView emptyView;
    private String[] items = {"拍照", "我的相册"};
    private boolean isHave = false;
    // 头像文件、上传头像的名称、本地图片uri
    private File imageFile;
    private PhotoAlbum photoAlbum;
    private Uri imageUri; // 图片路径
    private String saveFileName = "";
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    Bundle data = msg.getData();
                    PhotoAlbum photo= (PhotoAlbum) data.getSerializable("list");
                    if (photo == null) {
                        isHave = false;
                        emptyView.setNotify("暂无图片");
                    } else {
                        isHave = true;
                        photoAlbum = photo;
                        emptyView.setEmptyViewGone();
                        list.clear();
                        list.addAll(photoAlbum.getImg());
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }

                    break;
                case PIC_SUCCESS:
                    Bundle data1 = msg.getData();
                    BmobFile bmobFile = (BmobFile) data1.getSerializable("pic");
                    list.add(0, bmobFile);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                    break;
                case SAVE_SUCCESS:
                    dialog.dismiss();
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void findViewByIDS() {
        emptyView = new EmptyView(this);
        title = findViewsById(R.id.top_tv_title);
        add = findViewsById(R.id.top_tv_right);
        add.setVisibility(View.VISIBLE);
        recyclerView = findViewsById(R.id.recyclerView);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        initData();
        bind();
    }

    private void bind() {
        findViewsById(R.id.top_rl_right).setOnClickListener(this);
        adapter = new ImgAdapter(this,list);
        recyclerView.setLayoutManager(new GridLayoutManager(this,3));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
    }

    private void initData() {
        title.setText("添加照片");
        bmobUtils = new BmobUtils(this);
        Intent intent = getIntent();
        if (intent.getIntExtra("id", 0) == 1) {//为1没有弹窗，为0有
            UserInfo userInfo = (UserInfo) intent.getSerializableExtra("photo");
            add.setVisibility(View.GONE);
            findViewsById(R.id.top_rl_right).setVisibility(View.GONE);
            bmobUtils.findFriendPhoto(userInfo,SUCCESS,handler);
        }else {
            add.setText("添加");
            bmobUtils.queryPhoto(loginuser,SUCCESS,handler);
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_rl_right:
                showActionSheetDialog(items);
                break;
        }
    }

    //    //头像选择对话框
    private void showActionSheetDialog(String[] items) {
        ActionSheet actionSheet = new ActionSheet(this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (int i = 0; i < items.length; i++) {
            actionSheet.addSheetItem(items[i], ActionSheet.SheetItemColor.Blue, PhotoActivity.this);
        }
        actionSheet.show();

    }
    @Override
    public void onClick(int which) {
        switch (which) {
            case TAKE_PHOTO:
                //拍照
                imageFile = ImageUploadUtil.createImageFile(ImageUploadUtil.CAMERA_SAVEDIR2, ImageUploadUtil.createImageName());
                startActivityForResult(ImageUploadUtil.intentImageCapture(imageFile), ImageUploadUtil.TAKE_PHOTO);
                break;
            case CHOOSE_PHOTO:
                //从相册选择
                startActivityForResult(ImageUtil.intentChooseImg(),
                        CHOOSE_PHOTO);
                break;
        }
    }
    //
//    /**
//     * Activity回调事件处理
//     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == 0) {
                    return;
                }
                //拍照
                ImageUtil.paizhaocreateImagefile(this, imageFile);
                if (imageFile == null) {
                    ToastUtils.shortToast(this, "图片太大无法上传");
                    return;
                }
                doSendThread();//上传图片
                break;
            case CHOOSE_PHOTO:
                //相册
                if (resultCode == 0) return;
                imageUri = data.getData();
                imageFile = MyApplication.getInstance().createimagefile(imageUri, getVmWidth(), getVmHeight());
                if (imageFile == null) {
                    ToastUtils.shortToast(this, "imageFile为空2");
                    return;
                }
                doSendThread();//上传图片
                break;
        }
    }
    //
//    /**
//     * 上传头像
//     */
    private void doSendThread() {
        dialog = ProgressDialog.show(this, null, "正在上传图片");
        BmobFile bmobFile = new BmobFile(imageFile);
        bmobUtils.upLoadPic(bmobFile,PIC_SUCCESS,handler);

    }
    // 捕获返回键的方法1
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        && event.getRepeatCount() == 0
        Intent intent = getIntent();
        if (intent.getIntExtra("id", 0) == 1) {//去掉返回的弹窗
            finish();
        } else {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                // 按下BACK，同时没有重复
                back();
            }
        }

        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void backClick(View view) {
        Intent intent = getIntent();
        if (intent.getIntExtra("id", 0) == 1) {//去掉返回
            finish();
        } else {
            back();
        }

    }

    public void back(){
        final MyAlertDialog logDialog = new MyAlertDialog(this);
        logDialog.builder()
                .setTitle("退出提示")
                .setMsg("是否要退出？")
                .setNegativeButton("仅退出", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                })
                .setPositiveButton("退出并保存", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog = ProgressDialog.show(PhotoActivity.this, null, "正在保存");
                        if (isHave){
                            photoAlbum.setImg(list);
                            bmobUtils.updatePic(photoAlbum,SAVE_SUCCESS,handler);
                        }else {

                            PhotoAlbum photoAlbum = new PhotoAlbum();
                            photoAlbum.setId(loginuser.getId());
                            photoAlbum.setImg(list);
                            bmobUtils.savePic(photoAlbum,SAVE_SUCCESS,handler);
                        }

                    }
                })
                .show();
    }
}
